<template>
  <div class="csv-generator-container">
    <div class="header">
      <h1>CSV造数工具</h1>
      <p>上传CSV文件，扩充数据并导出</p>
    </div>

    <!-- 文件上传区域 -->
    <div class="upload-section">
      <div class="upload-area" @click="triggerFileInput" @drop="handleDrop" @dragover.prevent>
        <input
          ref="fileInput"
          type="file"
          accept=".csv"
          @change="handleFileUpload"
          style="display: none"
        />
        <div class="upload-content">
          <font-awesome-icon :icon="['fas', 'cloud-upload-alt']" class="upload-icon" />
          <p>点击或拖拽CSV文件到此处</p>
          <p class="upload-hint">支持UTF-8编码的CSV文件</p>
        </div>
      </div>
    </div>

    <!-- 数据预览和配置区域 -->
    <div v-if="csvData.length > 0" class="data-section">
      <div class="section-header">
        <h2>数据预览与配置</h2>
        <div class="controls">
          <button @click="previewData" class="btn btn-primary">
            <font-awesome-icon :icon="['fas', 'eye']" />
            预览数据
          </button>
          <button @click="generateData" class="btn btn-success">
            <font-awesome-icon :icon="['fas', 'magic']" />
            生成扩充数据
          </button>
          <button @click="exportCsv" class="btn btn-export">
            <font-awesome-icon :icon="['fas', 'download']" />
            导出CSV
          </button>
        </div>
      </div>

      <!-- 生成设置 -->
      <div class="generation-settings">
        <h3>生成设置</h3>
        <div class="settings-grid">
          <div class="setting-item">
            <label>扩充行数：</label>
            <input
              v-model.number="generationSettings.targetRows"
              type="number"
              min="1"
              max="100000"
            />
          </div>
          <div class="setting-item">
            <label>唯一编码前缀：</label>
            <input v-model="generationSettings.uniquePrefix" placeholder="如：USER_" />
          </div>
          <div class="setting-item">
            <label>起始编号：</label>
            <input v-model.number="generationSettings.startNumber" type="number" min="1" />
          </div>
        </div>
      </div>

      <!-- 数据预览表格 -->
      <div v-if="previewRows.length > 0" class="data-preview">
        <h3>数据预览 (显示前10行)</h3>
        <div class="table-container">
          <table class="data-table">
            <thead>
            <tr>
              <th v-for="column in columns" :key="column.name">{{ column.name }}</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="(row, rowIndex) in previewRows" :key="rowIndex">
              <td v-for="column in columns" :key="column.name">
                <div class="cell-content">
                  {{ row[column.name] }}
                </div>
              </td>
            </tr>
            </tbody>
          </table>
        </div>
      </div>

      <!-- 列配置 -->
      <div class="columns-config">
        <h3>列配置</h3>
        <div class="table-container">
          <table class="config-table">
            <thead>
            <tr>
              <th>列名</th>
              <th>类型</th>
              <th>启用扩充</th>
              <th>生成方式</th>
              <th>配置选项</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="(column, index) in columns" :key="index">
              <td class="column-name">{{ column.name }}</td>
              <td class="column-type">{{ column.type }}</td>
              <td class="column-enabled">
                <label class="checkbox-label">
                  <input
                    type="checkbox"
                    v-model="column.enabled"
                    @change="updateColumnConfig(index)"
                  />
                  <span class="checkmark"></span>
                </label>
              </td>
              <td class="column-generation">
                <select v-model="column.generationType" @change="updateColumnConfig(index)">
                  <option value="random">随机字符串</option>
                  <option value="unique">唯一值</option>
                  <option value="dropdown">下拉框随机选择</option>
                  <option value="increment">递增数字</option>
                  <option value="copy">复制原值</option>
                </select>
              </td>
              <td class="column-options">
                <div v-if="column.generationType === 'dropdown'" class="dropdown-options">
                    <textarea
                      v-model="column.dropdownOptions"
                      placeholder="输入选项，每行一个"
                      rows="3"
                    ></textarea>
                </div>
                <div v-if="column.generationType === 'random'" class="random-settings">
                  <input
                    v-model.number="column.randomLength"
                    type="number"
                    placeholder="长度"
                    min="1"
                    max="50"
                  />
                </div>
                <div v-if="column.generationType === 'unique'" class="unique-settings">
                  <span class="info-text">使用全局唯一编码前缀</span>
                </div>
                <div v-if="column.generationType === 'increment'" class="increment-settings">
                  <span class="info-text">从起始编号开始递增</span>
                </div>
                <div v-if="column.generationType === 'copy'" class="copy-settings">
                  <span class="info-text">保持原始数据不变</span>
                </div>
              </td>
            </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>

    <!-- 统计信息 -->
    <div v-if="csvData.length > 0" class="stats-section">
      <div class="stats-grid">
        <div class="stat-item">
          <span class="stat-label">原始行数：</span>
          <span class="stat-value">{{ csvData.length }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-label">目标行数：</span>
          <span class="stat-value">{{ generationSettings.targetRows }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-label">列数：</span>
          <span class="stat-value">{{ columns.length }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'

interface Column {
  name: string
  type: string
  enabled: boolean
  generationType: 'random' | 'unique' | 'dropdown' | 'increment' | 'copy'
  dropdownOptions: string
  randomLength: number
}

interface GenerationSettings {
  targetRows: number
  uniquePrefix: string
  startNumber: number
}

const fileInput = ref<HTMLInputElement>()
const csvData = ref<any[]>([])
const columns = ref<Column[]>([])
const previewRows = ref<any[]>([])
const generatedData = ref<any[]>([])

const generationSettings = reactive<GenerationSettings>({
  targetRows: 1000,
  uniquePrefix: 'ID_',
  startNumber: 1,
})

// 触发文件选择
const triggerFileInput = () => {
  fileInput.value?.click()
}

// 处理文件拖拽
const handleDrop = (event: DragEvent) => {
  event.preventDefault()
  const files = event.dataTransfer?.files
  if (files && files.length > 0) {
    const file = files[0]
    if (file.type === 'text/csv' || file.name.endsWith('.csv')) {
      processFile(file)
    }
  }
}

// 处理文件上传
const handleFileUpload = (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  if (file) {
    processFile(file)
  }
}

// 处理CSV文件
const processFile = (file: File) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    const content = e.target?.result as string
    parseCsv(content)
  }
  reader.readAsText(file, 'UTF-8')
}

// 解析CSV内容
const parseCsv = (content: string) => {
  const lines = content.split('\n').filter((line) => line.trim())
  if (lines.length === 0) return

  // 解析表头
  const headers = parseCsvLine(lines[0])
  columns.value = headers.map((header) => ({
    name: header,
    type: 'string',
    enabled: true,
    generationType: 'copy' as const,
    dropdownOptions: '',
    randomLength: 8,
  }))

  // 解析数据行
  csvData.value = lines.slice(1).map((line) => {
    const values = parseCsvLine(line)
    const row: any = {}
    headers.forEach((header, index) => {
      row[header] = values[index] || ''
    })
    return row
  })

  // 自动预览
  previewData()
}

// 解析CSV行
const parseCsvLine = (line: string): string[] => {
  const result: string[] = []
  let current = ''
  let inQuotes = false

  for (let i = 0; i < line.length; i++) {
    const char = line[i]

    if (char === '"') {
      inQuotes = !inQuotes
    } else if (char === ',' && !inQuotes) {
      result.push(current.trim())
      current = ''
    } else {
      current += char
    }
  }

  result.push(current.trim())
  return result
}

// 更新列配置
const updateColumnConfig = (index: number) => {
  // 配置更新逻辑
}

// 预览数据
const previewData = () => {
  if (generatedData.value.length > 0) {
    previewRows.value = generatedData.value.slice(0, 10)
  } else {
    previewRows.value = csvData.value.slice(0, 10)
  }
}

// 生成扩充数据
const generateData = () => {
  const newData: any[] = []
  const uniqueValues = new Set<string>()

  for (let i = 0; i < generationSettings.targetRows; i++) {
    const row: any = {}

    columns.value.forEach((column, colIndex) => {
      if (column.enabled) {
        switch (column.generationType) {
          case 'random':
            row[column.name] = generateRandomString(column.randomLength)
            break
          case 'unique':
            const uniqueValue = generateUniqueValue(column.name, i, uniqueValues)
            row[column.name] = uniqueValue
            break
          case 'dropdown':
            const options = column.dropdownOptions.split('\n').filter((opt) => opt.trim())
            if (options.length > 0) {
              row[column.name] = options[Math.floor(Math.random() * options.length)]
            } else {
              row[column.name] = ''
            }
            break
          case 'increment':
            row[column.name] = String(generationSettings.startNumber + i)
            break
          case 'copy':
            if (csvData.value.length > 0) {
              const originalRow = csvData.value[i % csvData.value.length]
              row[column.name] = originalRow[column.name] || ''
            }
            break
        }
      } else {
        // 保持原值
        if (csvData.value.length > 0) {
          const originalRow = csvData.value[i % csvData.value.length]
          row[column.name] = originalRow[column.name] || ''
        }
      }
    })

    newData.push(row)
  }

  generatedData.value = newData
  previewData()
}

// 生成随机字符串
const generateRandomString = (length: number): string => {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  let result = ''
  for (let i = 0; i < length; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  return result
}

// 生成唯一值
const generateUniqueValue = (
  columnName: string,
  index: number,
  uniqueValues: Set<string>,
): string => {
  let value = `${generationSettings.uniquePrefix}${generationSettings.startNumber + index}`
  let counter = 0

  while (uniqueValues.has(value)) {
    value = `${generationSettings.uniquePrefix}${generationSettings.startNumber + index}_${counter}`
    counter++
  }

  uniqueValues.add(value)
  return value
}

// 导出CSV
const exportCsv = () => {
  try {
    const dataToExport = generatedData.value.length > 0 ? generatedData.value : csvData.value
    if (dataToExport.length === 0) {
      alert('没有数据可以导出')
      return
    }

    if (!columns.value || columns.value.length === 0) {
      alert('没有列配置信息')
      return
    }

    const headers = columns.value.map((col) => col.name)
    const csvContent = [
      headers.join(','),
      ...dataToExport.map((row) =>
        headers
          .map((header) => {
            try {
              const value = row[header]
              // 确保值为字符串类型，处理各种数据类型
              let stringValue = ''
              if (value === null || value === undefined) {
                stringValue = ''
              } else if (typeof value === 'string') {
                stringValue = value
              } else if (typeof value === 'number' || typeof value === 'boolean') {
                stringValue = String(value)
              } else {
                stringValue = String(value)
              }

              // 如果值包含逗号、引号或换行符，需要用引号包围
              if (
                stringValue.includes(',') ||
                stringValue.includes('"') ||
                stringValue.includes('\n')
              ) {
                return `"${stringValue.replace(/"/g, '""')}"`
              }
              return stringValue
            } catch (error) {
              console.error('处理单元格值时出错:', error, 'header:', header, 'value:', row[header])
              return ''
            }
          })
          .join(','),
      ),
    ].join('\n')

    // 添加BOM以确保UTF-8编码
    const BOM = '\uFEFF'
    const blob = new Blob([BOM + csvContent], { type: 'text/csv;charset=utf-8;' })
    const link = document.createElement('a')
    link.href = URL.createObjectURL(blob)
    link.download = `generated_data_${new Date().toISOString().slice(0, 10)}.csv`
    link.click()

    // 清理URL对象
    setTimeout(() => {
      URL.revokeObjectURL(link.href)
    }, 100)

    console.log('CSV导出成功，数据行数:', dataToExport.length)
  } catch (error) {
    console.error('导出CSV时出错:', error)
    alert('导出失败，请检查数据格式或重试')
  }
}
</script>

<style scoped lang="scss">
.csv-generator-container {
  width: 100%;
  min-height: 100vh;
  background: #f5f7fa;
  padding: 20px;
  box-sizing: border-box;
  overflow-y: auto;
  overflow-x: hidden;
}

.header {
  text-align: center;
  margin-bottom: 30px;
  background: #fff;
  padding: 30px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

  h1 {
    color: #333;
    margin-bottom: 10px;
    font-size: 28px;
    font-weight: 600;
  }

  p {
    color: #666;
    font-size: 16px;
    margin: 0;
  }
}

.upload-section {
  margin-bottom: 30px;
  background: #fff;
  padding: 30px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.upload-area {
  border: 2px dashed #ddd;
  border-radius: 8px;
  padding: 40px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #fafbfc;

  &:hover {
    border-color: #42b983;
    background: #f8fffe;
  }

  .upload-content {
    .upload-icon {
      font-size: 48px;
      color: #42b983;
      margin-bottom: 15px;
    }

    p {
      margin: 5px 0;
      color: #666;

      &.upload-hint {
        font-size: 14px;
        color: #999;
      }
    }
  }
}

.data-section {
  background: #fff;
  padding: 30px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 30px;

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;
    padding-bottom: 20px;
    border-bottom: 1px solid #eee;

    h2 {
      color: #333;
      margin: 0;
      font-size: 24px;
      font-weight: 600;
    }

    .controls {
      display: flex;
      gap: 12px;
      flex-wrap: wrap;
    }
  }
}

.btn {
  padding: 10px 20px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s ease;
  white-space: nowrap;

  &.btn-primary {
    background: #42b983;
    color: white;

    &:hover {
      background: #3aa876;
      transform: translateY(-1px);
      box-shadow: 0 4px 12px rgba(66, 185, 131, 0.3);
    }
  }

  &.btn-success {
    background: #28a745;
    color: white;

    &:hover {
      background: #218838;
      transform: translateY(-1px);
      box-shadow: 0 4px 12px rgba(40, 167, 69, 0.3);
    }
  }

  &.btn-export {
    background: #007bff;
    color: white;

    &:hover {
      background: #0056b3;
      transform: translateY(-1px);
      box-shadow: 0 4px 12px rgba(0, 123, 255, 0.3);
    }
  }
}

.generation-settings {
  margin-bottom: 40px;

  h3 {
    color: #333;
    margin-bottom: 20px;
    font-size: 20px;
    font-weight: 600;
  }

  .settings-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 20px;
  }

  .setting-item {
    display: flex;
    flex-direction: column;
    gap: 8px;

    label {
      font-weight: 600;
      color: #333;
      font-size: 14px;
    }

    input {
      padding: 10px 14px;
      border: 1px solid #ddd;
      border-radius: 6px;
      font-size: 14px;
      transition: all 0.3s ease;

      &:focus {
        outline: none;
        border-color: #42b983;
        box-shadow: 0 0 0 3px rgba(66, 185, 131, 0.1);
      }
    }
  }
}

.data-preview {
  margin-bottom: 40px;

  h3 {
    color: #333;
    margin-bottom: 20px;
    font-size: 20px;
    font-weight: 600;
  }

  .table-container {
    overflow-x: auto;
    border: 1px solid #e1e5e9;
    border-radius: 10px;
    background: #fff;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

    &::-webkit-scrollbar {
      height: 8px;
    }

    &::-webkit-scrollbar-track {
      background: #f1f1f1;
      border-radius: 4px;
    }

    &::-webkit-scrollbar-thumb {
      background: #c1c1c1;
      border-radius: 4px;

      &:hover {
        background: #a8a8a8;
      }
    }
  }

  .data-table {
    width: 100%;
    border-collapse: collapse;
    min-width: 600px;

    th,
    td {
      padding: 12px 16px;
      text-align: left;
      border-bottom: 1px solid #eee;
      font-size: 14px;
      vertical-align: top;
    }

    th {
      background: #f8f9fa;
      font-weight: 600;
      color: #333;
      position: sticky;
      top: 0;
      z-index: 10;
    }

    td {
      color: #666;
    }

    tr:hover {
      background: #f8f9fa;
    }

    tr:last-child td {
      border-bottom: none;
    }

    .cell-content {
      max-height: 60px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      line-height: 1.4;
    }
  }
}

.columns-config {
  margin-bottom: 40px;

  h3 {
    color: #333;
    margin-bottom: 20px;
    font-size: 20px;
    font-weight: 600;
  }

  .table-container {
    overflow-x: auto;
    border: 1px solid #e1e5e9;
    border-radius: 10px;
    background: #fff;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }

  .config-table {
    width: 100%;
    border-collapse: collapse;
    min-width: 600px;

    th,
    td {
      padding: 12px 16px;
      text-align: left;
      border-bottom: 1px solid #eee;
      font-size: 14px;
    }

    th {
      background: #f8f9fa;
      font-weight: 600;
      color: #333;
      position: sticky;
      top: 0;
      z-index: 10;
    }

    td {
      color: #666;
    }

    tr:hover {
      background: #f8f9fa;
    }

    tr:last-child td {
      border-bottom: none;
    }
  }

  .column-name {
    font-weight: 600;
    color: #333;
    font-size: 16px;
  }

  .column-type {
    font-size: 12px;
    color: #666;
    background: #e9ecef;
    padding: 4px 8px;
    border-radius: 6px;
    font-weight: 500;
  }

  .column-enabled {
    .checkbox-label {
      display: flex;
      align-items: center;
      gap: 8px;
      font-size: 14px;
      font-weight: 500;
      color: #555;
      cursor: pointer;

      input[type='checkbox'] {
        width: 16px;
        height: 16px;
        cursor: pointer;
        accent-color: #42b983;
      }
    }
  }

  .column-generation {
    select {
      padding: 8px 12px;
      border: 1px solid #ddd;
      border-radius: 6px;
      font-size: 14px;
      transition: all 0.3s ease;
      width: 100%;
      max-width: 150px;

      &:focus {
        outline: none;
        border-color: #42b983;
        box-shadow: 0 0 0 3px rgba(66, 185, 131, 0.1);
      }
    }
  }

  .column-options {
    .dropdown-options {
      textarea {
        resize: vertical;
        min-height: 80px;
        padding: 8px 12px;
        border: 1px solid #ddd;
        border-radius: 6px;
        font-size: 14px;
        transition: all 0.3s ease;
        width: 100%;
        max-width: 200px;

        &:focus {
          outline: none;
          border-color: #42b983;
          box-shadow: 0 0 0 3px rgba(66, 185, 131, 0.1);
        }
      }
    }

    .random-settings {
      input {
        padding: 8px 12px;
        border: 1px solid #ddd;
        border-radius: 6px;
        font-size: 14px;
        transition: all 0.3s ease;
        width: 100%;
        max-width: 100px;

        &:focus {
          outline: none;
          border-color: #42b983;
          box-shadow: 0 0 0 3px rgba(66, 185, 131, 0.1);
        }
      }
    }

    .info-text {
      font-size: 12px;
      color: #666;
      font-style: italic;
      display: block;
      margin-top: 4px;
    }
  }
}

.stats-section {
  background: #fff;
  padding: 30px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

  .stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
    gap: 20px;
  }

  .stat-item {
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    padding: 20px;
    border-radius: 10px;
    text-align: center;
    border: 1px solid #e1e5e9;
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
    }

    .stat-label {
      display: block;
      font-size: 14px;
      color: #666;
      margin-bottom: 8px;
      font-weight: 500;
    }

    .stat-value {
      display: block;
      font-size: 28px;
      font-weight: bold;
      color: #42b983;
    }
  }
}

@media (max-width: 768px) {
  .csv-generator-container {
    padding: 10px;
  }

  .header,
  .upload-section,
  .data-section,
  .stats-section {
    padding: 20px;
  }

  .section-header {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;

    .controls {
      justify-content: center;
      flex-wrap: wrap;
    }
  }

  .config-table {
    min-width: 500px;

    th,
    td {
      padding: 8px 12px;
      font-size: 13px;
    }

    .column-generation select {
      max-width: 120px;
      font-size: 13px;
    }

    .column-options {
      .dropdown-options textarea {
        max-width: 150px;
        min-height: 60px;
      }

      .random-settings input {
        max-width: 80px;
      }
    }
  }

  .settings-grid {
    grid-template-columns: 1fr;
  }

  .stats-grid {
    grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
  }

  .btn {
    padding: 8px 16px;
    font-size: 13px;
  }
}

@media (max-width: 480px) {
  .csv-generator-container {
    padding: 5px;
  }

  .header,
  .upload-section,
  .data-section,
  .stats-section {
    padding: 15px;
  }

  .upload-area {
    padding: 30px 20px;
  }

  .config-table {
    min-width: 400px;

    th,
    td {
      padding: 6px 8px;
      font-size: 12px;
    }

    .column-generation select {
      max-width: 100px;
      font-size: 12px;
      padding: 6px 8px;
    }

    .column-options {
      .dropdown-options textarea {
        max-width: 120px;
        min-height: 50px;
        padding: 6px 8px;
        font-size: 12px;
      }

      .random-settings input {
        max-width: 60px;
        padding: 6px 8px;
        font-size: 12px;
      }

      .info-text {
        font-size: 11px;
      }
    }
  }
}
</style>
